from fastapi import APIRouter, Query, Depends

from application.utils import get_rich_logger
from authentication.jwt import get_current_user
from domain.authentication import User
from domain.juice import *
from juicefs.file_system import add_new_file_system_record, update_juicefs_configuration, delete_file_system_record, \
    view_juicefs_configuration

logger = get_rich_logger()

juicefs_router = APIRouter(
    prefix="/juicefs",
    tags=['juicefs']
)


@juicefs_router.post("/create")
async def create_new_file_system(
        juicefs_conf: FileSystem,
        current_user: User = Depends(get_current_user)
):
    fs_conf = FileSystemInDB(
        name=juicefs_conf.name,
        uuid=current_user.uuid.hex,
        fs_definition=juicefs_conf.json()
    )
    logger.debug(f"Distributed file system config: {fs_conf}")
    new_record_response = await add_new_file_system_record(
        new_record=fs_conf,
        user=current_user
    )
    return new_record_response


@juicefs_router.get("/fetch")
async def get_file_system_info(
        juicefs_id: str | None = Query(
            default=None,
            alias="juicefs-id",
            title="Target JuiceFS record id.",
            description="The File system intended to get information about.",
        ),
        current_user: User = Depends(get_current_user)
):
    metadata_record = await view_juicefs_configuration(
        target_fs_id=juicefs_id,
        user=current_user
    )
    return metadata_record


@juicefs_router.patch("/update")
async def update_file_system_config(
        new_juicefs_conf: FileSystem,
        juicefs_id: str = Query(
            ...,
            alias="juicefs-id",
            title="Target JuiceFS record id.",
            description="The File system intended to update.",
        ),
        current_user: User = Depends(get_current_user)
):
    updated_record = await update_juicefs_configuration(
        user=current_user,
        update_record_id=juicefs_id,
        new_fs_conf=new_juicefs_conf
    )
    return updated_record


@juicefs_router.delete("/delete")
async def delete_file_system(
        juicefs_id: str = Query(
            ...,
            alias="juicefs-id",
            title="Target JuiceFS record id.",
            description="The File system intended to be deleted.",
        ),
        current_user: User = Depends(get_current_user)
):
    ret = await delete_file_system_record(
        target_fs_id=juicefs_id,
        user=current_user
    )
    return ret
